# szdzld insert
import csv
import math
import re
import shutil
from datetime import datetime

import functions


def number():
    # input lunch id(int)
    # You can search launch in https://www.orbitalfocus.uk/Diaries/Launches/Launches.php?year={year}#{id}

    while True:
        num = input("Enter the launch id(xxx):")
        if bool(re.match(r'\d{3}', num)):
            return int(num)
        else:
            print("Invalid parameter")


def date():
    # input launch docx(string)
    # date format:{year-month-day}
    # Launch of China is UTF+8,other is UTF,please confirm the date is correct

    while True:
        text = input("Enter the launch date(xxxx-xx-xx):")
        try:
            datetime.strptime(text, '%Y-%m-%d')
            return text
        except ValueError:
            print("Invalid parameter")


def time():
    # input launch time(string)
    # time format:{hour:minute}
    # Launch of China is UTF+8,other is UTF,please confirm the time is correct

    while True:
        text = input("Enter the launch time(xxxx):")
        try:
            datetime.strptime(text, '%H%M')
            time_string = datetime.strptime(text, '%H%M')
            dt = time_string.strftime('%H:%M')
            return dt
        except ValueError:
            print("Invalid parameter")


def site():
    # input launch site(string)
    # site is released in site_info.csv,if it has new launch site,please enter in csv file
    # if it is sea launch,user should enter latitude

    with open('data/docx/site_info.csv', 'r', newline='') as file:
        reader = csv.DictReader(file)
        file_row = 0
        site_dict = {}
        for row in reader:
            if row['COUNTRY'] == in_country:
                file_row = file_row + 1
                print(f'{file_row}: {row["SITENAME"]}')
                site_dict[f'{file_row}'] = f'{row["SITENAME"]}'
    while True:
        site_code = input("Enter the site code\n"
                          "if rocket is sea launch please enter 's':")
        if site_code in site_dict:
            return site_dict[site_code]
        elif site_code == "s":
            latitude = input("Enter sea launch latitude(°):")
            try:
                float(latitude) in range(-90, 90)
                return float(latitude)
            except ValueError:
                print("Invalid parameter")
        else:
            print("Invalid parameter")


def rocket():
    # input launch rocket(string)

    with open('data/docx/rocket_info .csv', 'r', newline='') as file:
        reader = csv.DictReader(file)
        file_row = 0
        rocket_dict = {}
        for row in reader:
            if row['COUNTRY'] == in_country:
                file_row = file_row + 1
                print(f'{file_row}: {row["ROCKET"]}')
                rocket_dict[f'{file_row}'] = f'{row["ROCKET"]}'
    while True:
        rocket_code = input("Enter the rocket code:")
        if rocket_code in rocket_dict:
            return rocket_dict[rocket_code]
        else:
            print("Invalid parameter")


def mass():
    # input payload mass(float)
    # if user do not know payload mass,return '0.0' to request default mass
    # default mass is max payload mass in this orbit

    while True:
        num = input("If mass is default please enter 'D'\n"
                    "Enter the payload mass(kg):")
        if functions.is_number(num):
            return float(num)
        elif num == 'D':
            return 0.0
        else:
            print("Invalid parameter")


def ap():
    # input orbit Apogee(int) Perigee
    # the number should be more than Perigee

    while True:
        num = input("Enter Ap.(km):")
        if functions.is_number(num):
            return int(num)
        else:
            print("Invalid parameter")


def pe():
    # input orbit Perigee(int)
    # the number should be less than Apogee

    while True:
        num = input("Enter Pe.(km):")
        if functions.is_number(num):
            return int(num)
        else:
            print("Invalid parameter")


def In():
    # input Inclination(float)

    while True:
        num = input("Enter In.(°):")
        if functions.is_number(num):
            return float(num)
        else:
            print("Invalid parameter")


def ot():
    # input orbit type(string)
    # other escape should user enter C3 energy

    while True:
        print("1: LEO\n2: SSO\n3: MEO\n4: GTO\n5: GEO"
              "\n6: HEO\n7: TLI\n8: Other escape")

        ot_dict = {
            '1': 'LEO',
            '2': 'SSO',
            '3': 'MEO',
            '4': 'GTO',
            '5': 'GEO',
            '6': 'HEO',
            '7': 'TLI',
            '8': 'Other escape'
        }
        ot_code = input("Enter orbit properties:")
        if ot_code in ot_dict:
            return ot_dict[ot_code]
        else:
            print("Invalid parameter")


def delta_v():
    # return launch delta v
    #

    r = int(in_pe) * 1000 + 6371000
    a = (int(in_ap) * 1000 + int(in_pe) * 1000 + 2 * 6371000) / 2
    b = 2 / r
    c = 1 / a
    v = math.sqrt(398600000000000 * (b - c))

    if functions.is_number(in_site):
        degree = float(in_site)
    else:
        site_data = functions.file_data('data/docx/site_info.csv', 'SITENAME', f'{in_site}', 'LATITUDE')
        sd = list(site_data)
        degree = float(sd[0] + sd[1] + "." + sd[3] + sd[4] + sd[6] + sd[7] + sd[9] + sd[10])

    ov = (1667 * math.cos(math.radians(degree))) / 3.6
    dv = v - ov
    return float(dv)


def orbit_energy():
    #

    if ce_switch == 0:
        oe = -39860000000000 / ((in_pe + in_ap + 12742) * 1000)
        return float(oe)
    else:
        return float(in_ce) * 2


def energy():
    #

    e = (in_oe + 62600000.0) * float(in_mass) / 1000000000000.0
    return float(e)


def success_data():
    while True:
        print(
            f"ID:{in_number}\nDate: {in_date}\nTime: {in_time}\nCountry: {in_country}\nSite: {in_site}\n"
            f"Rocket: {in_rocket}\nMass: {in_mass}kg\nOrbit: {in_pe}km x {in_ap}km {in_in}°\nType: {in_ot}\n"
        )

        wrong = input(
            "If the docx is wrong,please enter the docx code(e.g: i/d .etc)\nIf docx is no wrong,please enter 'n':")
        wrong_dict = ["i", "d", "t", "c", "s", "r", "m", "o", "t", "n"]
        if wrong in wrong_dict:
            return wrong
        else:
            print("Invalid parameter")


def failure_data():
    while True:
        print(
            f"Date: {in_date}\nTime: {in_time}\nCountry: {in_country}\n"
            f"Site: {in_site}\nRocket: {in_rocket}\n"
        )
        print()
        wrong = input(
            "If the docx is wrong,please enter the docx code(e.g: i/d .etc)\nIf docx is no wrong,please enter 'n':")
        wrong_dict = ["d", "t", "c", "s", "r", "n"]
        if wrong in wrong_dict:
            return wrong
        else:
            print("Invalid parameter")


in_number = number()
print()
in_date = date()
print()
in_time = time()
print()
in_country = functions.country()
print()
in_site = site()
print()
in_rocket = rocket()
print()
if in_number != 0:
    in_mass = mass()
    print()
    in_ap = ap()
    print()
    in_pe = pe()
    print()

    while True:
        if functions.is_orbit(in_ap, in_pe):
            break
        else:
            print("ap and pe are wrong, please reenter")
            in_ap = ap()
            in_pe = pe()

    in_in = In()
    print()
    in_ot = ot()
    print()

    if in_mass == 0.0:
        if in_ot in ["LEO", "SSO", "GTO"]:
            filename = 'data/docx/rocket_info .csv'
            column = 'ROCKET'
            search = in_rocket
            row_name = in_ot
            in_mass = functions.file_data(filename, column, search, row_name)
            if in_mass == '':
                in_mass = input("Mass has not default docx, please enter(kg):")
            else:
                pass
        else:
            in_mass = input("Mass has not default docx, please enter(kg):")
    else:
        pass

    in_ce = 0
    ce_switch = 0
    if in_ot == 'Other escape':
        in_ce = float(input("Please enter C3 energy(MJ):")) * 1000000.0
        ce_switch = 1
    else:
        pass

    print("Please confirm launch docx")

    wrong_code = success_data()
    while True:
        if wrong_code == "n":
            break
        elif wrong_code == "i":
            in_number = number()
            wrong_code = success_data()
        elif wrong_code == "d":
            in_date = date()
            wrong_code = success_data()
        elif wrong_code == "t":
            in_time = time()
            wrong_code = success_data()
        elif wrong_code == "c":
            in_country = functions.country()
            wrong_code = success_data()
        elif wrong_code == "s":
            in_site = site()
            wrong_code = success_data()
        elif wrong_code == "r":
            in_rocket = rocket()
            wrong_code = success_data()
        elif wrong_code == "m":
            in_mass = mass()
            wrong_code = success_data()
        elif wrong_code == "o":
            in_ap = ap()
            in_pe = pe()
            in_in = In()
            wrong_code = success_data()
        elif wrong_code == "t":
            in_ot = ot()
            wrong_code = success_data()

    in_dv = delta_v()
    in_oe = orbit_energy()
    if ce_switch == 0:
        in_ce = in_oe * 2
    else:
        pass
    in_e = energy()

    list_date = list(in_date)
    key_word = list_date[0] + list_date[1] + list_date[2] + list_date[3] + list_date[5] + list_date[6]
    if not functions.is_file(key_word):
        src = 'data/docx/template_launch_info.csv'
        dst = f'data/{key_word}_launch_ino.csv'
        shutil.copy(src, dst)
    else:
        pass

    in_data = [in_number, in_date, in_time, in_country, in_rocket, in_mass, in_ap, in_pe, in_in, in_ot, 'Success',
               in_dv, in_oe, in_ce, in_e]
    functions.write_to_csv(f'data/{key_word}_launch_ino.csv', in_data)

else:
    print("Please confirm launch docx")

    wrong_code = failure_data()
    while True:
        if wrong_code == "n":
            break
        elif wrong_code == "d":
            in_date = date()
            wrong_code = failure_data()
        elif wrong_code == "t":
            in_time = time()
            wrong_code = failure_data()
        elif wrong_code == "c":
            in_country = functions.country()
            wrong_code = failure_data()
        elif wrong_code == "s":
            in_site = site()
            wrong_code = failure_data()
        elif wrong_code == "r":
            in_rocket = rocket()
            wrong_code = failure_data()

    list_date = list(in_date)
    key_word = list_date[0] + list_date[1] + list_date[2] + list_date[3] + list_date[5] + list_date[6]
    if not functions.is_file(key_word):
        src = 'data/docx/template_launch_info.csv'
        dst = f'data/{key_word}_launch_ino.csv'
        shutil.copy(src, dst)
    else:
        pass

    in_data = [in_number, in_date, in_time, in_country, in_rocket, '', '', '', '', '', 'Failure', '', '', '', '']
    functions.write_to_csv(f'data/{key_word}_launch_ino.csv', in_data)
